<template>
	<section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" >
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

		<!--列表-->
		<template>
			<el-table :data="employees" highlight-current-row v-loading="listLoading"
       :row-key="getRowKeys"   ref="EmployeeTable" @selection-change="selsChange"  style="width: 100%;">
        <el-table-column type="selection" width="55" reserve-selection="true">
        </el-table-column>
        <el-table-column type="index" width="60" >
        </el-table-column>
        <el-table-column prop="username" label="员工名称" width="120" sortable>
        </el-table-column>
        <el-table-column prop="phone" label="员工电话" width="160" sortable>
        </el-table-column>
        <el-table-column prop="email" label="员工邮箱" width="160" >
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="100" >
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100" >
          <template scope="scope">
            <span v-if="scope.row.state==1" style="color: #13ce66">启用</span>
            <span v-else-if="scope.row.state==0" style="color: #8c939d">禁用</span>
          </template>
        </el-table-column>
        <el-table-column prop="department.name" label="部门" min-width="80" >
        </el-table-column>
        <el-table-column prop="shop.name" label="店铺" width="100" >
        </el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
		</template>
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals" style="float:right">
      </el-pagination>
      <!--      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
               :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
            </el-pagination>-->
    </el-col>
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="员工名称" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off" @focus="nextTick('username')"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off" @focus="nextTick('phone')"></el-input>
        </el-form-item>
        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off" @focus="nextTick('email')"></el-input>
        </el-form-item>
        <el-form-item label="员工密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off" @focus="nextTick('password')"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="saveForm.age" :min="0" :max="200" ></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.department_id"
                       :options="deptTree"
                       :props="{
            	checkStrictly: true,
                label: 'name', // 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
            }" clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item label="店铺">
          <!--el-select下拉框
            v-model="saveForm,manager._id"回显提交的内容的key
            placeholder="请选择"提示语
            el-option选项
            V-for="manager in managers"遍历
            :label="manager.label"回显内容
            :valve=:"manager,valve"提交的内容-->
          <el-select v-model="saveForm.shop_id" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="saveFormVisible = false">取消</el-button>
          <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
        </div>
    </el-dialog>
	</section>
</template>
<script>
import {editDepartment, getEmployeeList} from '../../api/api';
import util from "../../common/js/util";
	//import NProgress from 'nprogress'
	export default {
    data() {
      return {
        keyword: '',
        totals: 0,
        currentPage: 1,
        pageSize: 5,
        listLoading: false,
        sels: [],//列表选中列
        title: '',
        loading: false,
        employees: [],
        saveForm:{
          username:'',
          phone:'',
          email:'',
          salt:'',
          password:'',
          age:null,
          state:null,
          department_id:null,
          logininfo_id:null,
          shop_id:null,
        },
        saveFormVisible: false,//新增界面是否显示
        saveLoading: false,
        saveFormRules: {
          username: [
            {required: true, message: '请输入员工名称', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '请输入员工电话', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入员工电话', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入员工密码', trigger: 'blur'}
          ],
          age: [
            {required: true, message: '请输入员工电话', trigger: 'blur'}
          ],
        },
        deptTree: [],
        shops:[],
      }
    },
    methods: {
      nextTick(prop){
        this.$refs.saveForm.clearValidate(prop);
      },
      getRowKeys(row){
        return row.id;
      },
      //获取所有店铺
      getShops(){
        this.$http.get("/shop").then(res=>{
          this.shops=res.data;
        }).catch(res=>{
          this.$message.error("网络繁忙，请稍后重试【404】")
        })
      },
      //多选
      selsChange(sel) {
        this.sels = sel.map(row => row.id)
      },
      //高级查询
      keywordQuery() {
        this.currentPage = 1;
        this.getEmployee();
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getEmployee();
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getEmployee();
      },
      getDeptTree(id){
        this.$http.get("/department/deptTree/"+id).then(res=> {
          this.deptTree = res.data;
        }).catch(res=>{
          this.$message.error("网络繁忙，请稍后重试")
        })
      },
      //新增
      handleAdd() {
        this.title='新增';
        //获取部门树
        this.getDeptTree(-1);
        this.getShops();
        this.saveForm = {
          username:'',
          phone:'',
          email:'',
          salt:'',
          password:'',
          age:null,
          state:0,
          department_id:null,
          logininfo_id:null,
          shop_id:null,
        };
        //打开对话框
        this.saveFormVisible = true;
      },
      //编辑
      //显示编辑界面
      handleEdit: function (index, row) {
        this.title='编辑';
        //获取部门树
        this.getDeptTree(-1);
        this.getShops();
        //复制数据
        this.saveForm = Object.assign({}, row);
        //打开对话框
        this.saveFormVisible = true;
      },
      //获取用户列表
      getEmployee: function () {
        let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.keyword
        };
        this.loading = true;
        //NProgress.start();
        this.$http.post("/employee", para).then((res) => {
          this.employees = res.data.data;
          this.totals = res.data.totals;
          this.loading = false;
          //NProgress.done();
        });
      },
      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
          // let temp = { id: row.id };
          this.$http.delete("/employee/" + row.id).then(res => {
            this.listLoading = false;
            if (res.data.success) {
              this.$message.success(res.data.message);
              if (this.currentPage != 1 && this.totals % this.pageSize == 1
                  && this.currentPage == Math.ceil(this.totals / this.pageSize)) {
                this.currentPage = this.currentPage - 1;
              }
              this.getEmployee();
            } else {
              this.$message.error(res.data.message);
            }
          }).catch(res => {
            this.$message.error("网络繁忙，请稍后重试【404】")
          })
        }).catch(() => {
          this.$message.info("操作取消")
        });
      },
      //新增/编辑
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              //NProgress.start();
              let temps = Object.assign({}, this.saveForm);
              let temp = temps.department_id;
              if (temp && temp.length==0 ){
                temps.department_id=null;
              }else if (temp && temp.length>0) {
                temps.department_id=temp[temp.length-1];
              }
              this.$http.put("/employee", temps).then(res => {
                this.saveLoading = false;
                if (res.data.success) {
                  this.saveFormVisible = false;
                  this.$message.success(res.data.message);
                  if (this.title == '新增' && this.totals % this.pageSize == 0) {
                    this.totals += 1;
                  }
                  if (this.title == '新增') {
                    this.currentPage = Math.ceil(this.totals / this.pageSize);
                  }
                  this.getEmployee();
                } else {
                  this.$message.error(res.data.message);
                }
              }).catch(res => {
                {
                  this.$message.error("网络繁忙，请稍后重试【404】")
                }
              })
            }).catch(() => {
              this.$message.info("操作取消");
            });
          }
        });
      },
      //批量删除
      batchRemove: function () {
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          // NProgress.start();
          // let temp = { ids: ids };
          this.$http.patch("/employee", this.sels).then(res => {
            this.listLoading = false;
            if (res.data.success) {
              this.$message.success(res.data.message);
              this.sels=[],
              //清空多选框
              this.$refs.EmployeeTable.clearSelection();
              this.currentPage = 1;
              this.getEmployee();
            } else {
              this.$message.error(res.data.message);
            }
          }).catch(res => {
            this.$message.error("网络繁忙，请稍后重试【404】")
          })
        }).catch(() => {
          this.$message.info("操作取消")
        });
      },
      //编辑
      // editSubmit: function () {
      //   this.$refs.editForm.validate((valid) => {
      //     if (valid) {
      //       this.$confirm('确认提交吗？', '提示', {}).then(() => {
      //         this.editLoading = true;
      //         //NProgress.start();
      //         let temp = Object.assign({}, this.editForm);
      //         temp.birth = (!temp.birth || temp.birth == '') ? '' : util.formatDate.format(new Date(temp.birth), 'yyyy-MM-dd');
      //         editDepartment(temp).then((res) => {
      //           this.editLoading = false;
      //           //NProgress.done();
      //           this.$message({
      //             message: '提交成功',
      //             type: 'success'
      //           });
      //           this.$refs['editForm'].resetFields();
      //           this.editFormVisible = false;
      //           this.getEmployee();
      //         });
      //       });
      //     }
      //   });
      // },
    },

		mounted() {
			this.getEmployee();
		}
	}

</script>

<style scoped>

</style>